<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="dataForm" class="searchform" inline label-width="80px">

        <el-form-item :label="$t('bs.templateName')" prop="name">
          <el-input
            v-model="listQuery.name"
            class="filter-item"
            placeholder="模板名称"
            style="width: 204px;"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item :label="$t('bs.templateClassification')" prop="inc_type">
          <el-select v-model="listQuery.inc_type">
            <el-option v-for="item in types" :value="item.dict_value" :label="item.dict_key" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="创建日期" prop="url">-->
        <!--          <el-input-->
        <!--            v-model="listQuery.create_date"-->
        <!--            class="filter-item"-->
        <!--            placeholder="创建日期"-->
        <!--            style="width: 204px;"-->
        <!--            @keyup.enter.native="handleFilter"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-button v-waves class="filter-item" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>

        <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilterReset">
          {{$t('bs.reset')}}
        </el-button>

        <!--        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">-->
        <!--          {{ $t('table.add') }}-->
        <!--        </el-button>-->
      </el-form>

    </div>

    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;"
    >
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate"
            v-bp="'/bs/template/edit'"
          >
            {{$t("bs.add")}}
          </el-button>
<!--          <el-button-->
<!--            class="filter-item"-->
<!--            plain-->
<!--            size="small"-->
<!--            style="margin-left: 10px;"-->
<!--            type="primary"-->
<!--            @click="handleDeleteAll"-->
<!--          >-->
<!--            {{$t('bs.batchDelete')}}-->
<!--          </el-button>-->
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox v-for="item in fileds" v-model="item.is_show" false-label="0" true-label="1">
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column label="序号" width="55">
          <template slot-scope="{$index,row}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          type="selection"
          width="55"
        />

        <el-table-column v-if="fileds.name.is_show==1" :label="$t('bs.templateName')">
          <template slot-scope="{row}">
            {{ row.name }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.inc_type.is_show==1" label="模板类型" width="120">
          <template slot-scope="{row}">
            {{ row.inc_type }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.create_date.is_show==1" label="创建日期" width="180" align="center">
          <template slot-scope="{row}">
            {{ row.create_date?getdate(row.create_date):"" }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.is_default.is_show==1" :label="$t('bs.defaultTemplate')" width="80" align="center">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_default==1" type="success">是</el-tag>
            <el-tag v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.is_public.is_show==1" :label="$t('bs.IsPublic')" width="80" align="center">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_public==1" type="success">是</el-tag>
            <el-tag v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width" width="300">
          <template slot-scope="{row,$index}">
            <el-tooltip slot="reference" class="item" effect="dark" content="编辑" placement="bottom-start">

              <el-button  v-bp="'/bs/template/edit'" circle icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>

            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDelete(row.id)"
            >
              <el-tooltip slot="reference" class="item" effect="dark" content="删除" placement="bottom-start">
                <el-button
                  v-bp="'/bs/template/edit'"
                  icon="el-icon-delete"
                  size="small"
                  style="margin-left: 8px"
                />
              </el-tooltip>
            </el-popconfirm>

            <el-tooltip class="item" effect="dark" content="复制" placement="bottom-start">
              <el-button  v-bp="'/bs/template/edit'" style="margin-left: 8px" circle icon="el-icon-magic-stick" size="small" @click="handleCopy(row)" />
            </el-tooltip>
            <el-button  v-bp="'/bs/template/view'" icon="el-icon-edit" size="small" style="margin-left: 8px" @click="toeditTemplate(row)">编辑目录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page_no"
        :total="total"
        @pagination="getList"
      />

    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">

          <el-col :span="24">
            <el-form-item :label="$t('bs.templateClassification')" prop="inc_type">
              <el-select v-model="temp.inc_type">
                <el-option v-for="item in types" :value="item.dict_value" :label="item.dict_key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('bs.templateName')" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="创建日期" prop="create_date">-->
          <!--              <el-input v-model="temp.create_date"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item :label="$t('bs.defaultTemplate')" prop="is_default">
              <el-radio-group v-model="temp.is_default">
                <el-radio label="1">
                  是
                </el-radio>
                <el-radio label="0">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.IsPublic')" prop="is_default">
              <el-radio-group v-model="temp.is_public">
                <el-radio label="1">
                  是
                </el-radio>
                <el-radio label="0">
                  否
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button :loading="subloading" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, createData, updateData, delData, fetchDict, copyTpm, delTpl} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect'
import {saveTemplateOne} from "@/api/template"; // secondary package based on el-pagination

export default {
  name: 'Template',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      checked: true,
      tablesetvisible: false,
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      listLoading: true,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      queryMap: {},
      showReviewer: false,
      temp: {
        id: '', name: '', is_default: '0', create_data: '', inc_type: '', is_public: '0'
      },
      fileds: {
        name: { filed: 'name', title: '模板名称', is_show: '1' },
        create_date: { filed: 'create_date', title: '分类日期', is_show: '1' },
        inc_type: { filed: 'inc_type', title: '类型', is_show: '1' },
        is_default: { filed: 'is_default', title: '是否默认', is_show: '1' },
        is_public: { filed: 'is_public', title: '是否公用', is_show: '1' },
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '模板名称不能为空', trigger: 'change' }],
        inc_type: [{ required: true, message: '模板分类不能为空', trigger: 'change' }],
        is_default: [{ required: true, message: '为缺省模板，1为是，0为否不能为空', trigger: 'change' }]
      },
      downloadLoading: false,
      subloading: false,
      types: []

    }
  },
  created() {
    this.getList()

  },

  async mounted() {
    const department = await fetchDict('模板分类')
    this.types = department.data.items
    console.log('模板分类', this.types)
  },
  methods: {

    async handleCopy(row) {
      this.$confirm('您确认复制模板么?').then(() => {
        this.editloading = true
        copyTpm(row.id).then((res) => {
          console.log('res', res)
          this.$message.success('复制成功')
          this.getList()
          this.editloading = false
        }).catch(() => {
          this.editloading = false
        })
      })
    },
    toeditTemplate(row) {
      this.$router.push({ name: 'template_edit', params: { id: row.id, name: row.name }})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getdate(time) {
      var now = new Date(time * 1000)
      var y = now.getFullYear()
      var m = now.getMonth() + 1
      var d = now.getDate()
      return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + now.toTimeString().substr(0, 8)
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'sl_doc_template').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '', name: '', is_default: '0', create_data: '', inc_type: '', is_public: '0'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.create_date = parseInt(new Date().getTime() / 1000)
          let data=_.cloneDeep(this.temp);
          data.is_default=parseInt(data.is_default);
          data.is_public=parseInt(data.is_public);
          data.id=0;
          this.subloading = true
         // createData({ data: [data] }, 'sl_doc_template').then(() => {
            saveTemplateOne(data).then(() => {

            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })

            this.getList()
            this.subloading = false
          }).catch((e) => {
            this.subloading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
            let data=_.cloneDeep(this.temp);
            data.id=parseInt(data.id);
          data.is_default=parseInt(data.is_default);
          data.is_public=parseInt(data.is_public);
         // updateData({ data: [data] }, 'sl_doc_template').then(() => {
            saveTemplateOne(data).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id)
        }

        this.handleDelete(ids)
      })
    },
    handleDelete(id) {
      delTpl(id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 280px;
}
</style>

